package hander

import (
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"readme/api/request"
	"readme/consts"
	"readme/global"
	"readme/internal/dao"
	"readme/internal/model"
	"readme/pkg"
	"strconv"
	"time"
)

func SendSms(c *gin.Context) {
	var req request.SendSmsReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "验证失败",
			"code": 500,
			"data": err.Error(),
		})
		return
	}
	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(req.Mobile, strconv.Itoa(code))
	if err != nil {
		return
	}
	if *sms.Body.Code != "OK" {
		panic(*sms.Body.Message)
	}
	global.Rdb.Set("sendSms"+req.Source+req.Mobile, code, time.Minute*3)
	c.JSON(http.StatusOK, gin.H{
		"msg":  "成功",
		"code": 200,
		"data": "SendSms",
	})
}
func Login(c *gin.Context) {
	var req request.LoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "验证失败",
			"code": 500,
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneById(req.Id, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "用户不存在",
			"code": 500,
			"data": nil,
		})
		return
	}
	token, _ := pkg.NewJWT(consts.JWT_KEY).CreateToken(pkg.CustomClaims{
		ID: user.Id,
	})
	c.JSON(http.StatusOK, gin.H{
		"msg":  "成功",
		"code": 200,
		"data": token,
	})
}

func List(c *gin.Context) {
	var a []model.Article
	tx := global.DB.Order("likes desc").Find(&a)
	c.JSON(http.StatusOK, gin.H{
		"msg":  "成功",
		"code": 200,
		"data": tx,
	})
}
